import React, { Component } from "react";
import { message, Spin } from 'antd';
import Header from '../myComponents/header';
import { getQueryVariable } from '../../util/public'
import fetch from '../../util/fetch'
import BtnAlert from "../myComponents/btnAlert";
import { LgVideo, LgAudio } from "lancoo-web-ui";
import "./index.scss";

class NoticeDetail extends Component {
    constructor(props){
        super(props);
        this.state = {
            alertInfo: {},
            detail: {},
            loadVisible: true,
            noticeId: "",
            iframe: false
        };
    }
    componentDidMount(){
        //获取详情
        let id = getQueryVariable("noticeId") || sessionStorage.getItem("noticeId");
        if(getQueryVariable("iframe")){
            this.setState({
                iframe: true
            })
        }
        let url = window.BasicProxy;
        if(getQueryVariable("status") == 0){
            url += "api/notice/info/edit/detail"
        }else{
            url += "api/notice/info/release/detail"
        }
        fetch.get({
            url,
            params: {
                noticeId: id,
                eduId: sessionStorage.getItem("eduId"),
            }
        })
        .then((res)=>res.json())
        .then((result)=>{
            if(result.code === "200" && result.data){
                if(window.opener){
                    window.opener.postMessage(JSON.stringify({sysId: 220, operateType: "update"}), "*");
                }
                if(window.parent){
                    window.parent.postMessage(JSON.stringify({sysId: 220, operateType: "update"}), "*");
                }
                this.setState({
                    detail: result.data,
                    loadVisible: false,
                    noticeId: id
                })
            } else {
                message.error(result.msg);
                this.setState({
                    loadVisible: false
                })
            }
            
        })
    }
    //设置弹窗提示信息
    setAlert = (data) => {
        this.setState({
            alertInfo: data
        })
    }
    withdraw = () => {  //撤回
        let {
            detail
        } = this.state;
        this.setAlert({
            visible: true,
            title: "确定要撤回该通知吗？",  
            onCancel: () => {
              this.setAlert({});
            },
            onOk: function(){
              fetch.put({
                  url: window.BasicProxy + "api/notice/manage/callback?noticeId=" + detail.noticeId,
              })
              .then((res)=>res.json())
              .then((result)=>{
                  if(result.code === "200"){
                      message.success("撤回成功");
                      if(window.opener){
                          window.opener.postMessage(JSON.stringify({
                              sysId: 220, 
                              operateType: "reflash", 
                              btnName: detail.title,
                              noticeId: detail.noticeId
                          }), "*");
                      }
                      if(window.parent){
                          window.parent.postMessage(JSON.stringify({
                              sysId: 220, 
                              operateType: "reflash", 
                              btnName: detail.title,
                              noticeId: detail.noticeId
                          }), "*");
                      }
                      window.close();
                  }
              })
            }
        })
    }
    delete = () => {  // 删除
        let {
            detail
        } = this.state;
        this.setAlert({
            visible: true,
            title: "确定要删除该通知吗？",  
            onCancel: () => {
              this.setAlert({});
            },
            onOk: function(){
              fetch.delete({
                  url: window.BasicProxy + "api/notice/manage/del?noticeId=" + detail.noticeId
              })
              .then((res)=>res.json())
              .then((result)=>{
                  if(result.code === "200"){
                      message.success("删除成功");
                      if(window.opener){
                          window.opener.postMessage(JSON.stringify({
                              sysId: 220, 
                              operateType: "reflash", 
                              btnName: detail.title,
                              noticeId: detail.noticeId
                          }), "*");
                      }
                      if(window.parent){
                          window.parent.postMessage(JSON.stringify({
                              sysId: 220, 
                              operateType: "reflash", 
                              btnName: detail.title,
                              noticeId: detail.noticeId
                          }), "*");
                      }
                      window.close();
                  }
              })
            }
        })
    }
    showhtml(htmlString) {
        var html = { __html: htmlString };
        return <div dangerouslySetInnerHTML={html}></div>;
    }
    downFile = (data) => {
        // window.open(data.url);
        let xhr = new XMLHttpRequest();
        xhr.open("get", data.url, true);
        xhr.responseType = "blob";
        xhr.onreadystatechange = function(){
            if(xhr.readyState === 4 && xhr.status == 200){
                let blob = new Blob([xhr.response]);
                let url = window.URL.createObjectURL(blob);
                let a = document.createElement("a");
                a.href = url;
                a.download = data.name;
                a.click();
                // let event = new MouseEvent("click");
                // a.dispatchEvent(event);
                URL.revokeObjectURL(url);
            }
        }
        xhr.send();
    }
    render(){
        let {
            alertInfo,
            detail,
            loadVisible,
            noticeId,
            iframe
        } = this.state;
        if(loadVisible){
            return <Spin size="large" />
        }
        return (
            <div className="notice_detail">
                {
                    iframe?
                    "":
                    <Header
                      title="局校通知公告"
                      subtitle="局校通知详情"
                      helpPath=""
                      logoutPath="/api/commons/user/logout"
                    />
                }
                {
                    getQueryVariable("status") == '0'?
                    <div className="btn_container">
                        <span className="red_btn" onClick={this.delete}>删除</span>
                    </div>:
                    <div className="btn_container">
                        <span className="red_btn" onClick={this.withdraw}>撤回</span>
                    </div>
                }
                
                {
                    detail ? 
                    <div className='notice-details-all'>
                        <div className='notice-details-middle'>
                            <h1>{detail.title}</h1>
                            <p className='notice-details-message'><span> <i className='people-img'></i>{detail.userName}</span><span><i className='timer-img'></i>{detail.releaseTime || "--"}</span></p>
                            <p className='notice-details-border'></p>
                            <div className="notice-content notice-contect">{this.showhtml(detail.content)}</div>
                            <div className="notice-attachment-preview">
                              {
                                // 音频
                                Array.isArray(detail.attachments) && detail.attachments.length > 0 && detail.attachments[0].type == 3?
                                <LgAudio src={window.BasicProxy + detail.attachments[0].url} />:
                                ""
                              }
                              {
                                // 视频
                                Array.isArray(detail.attachments) && detail.attachments.length > 0 && detail.attachments[0].type == 4?
                                <LgVideo src={window.BasicProxy + detail.attachments[0].url} />:
                                ""
                              }
                            </div>
                            {detail.attachments &&detail.attachments.length !=0? <div className="notice-down-box">
                                <p><i></i>附件下载</p>
                                {
                                    detail.attachments.map(item=>{
                                        let {
                                            name,url,size,attachmentId
                                        } = item
                                        return (
                                            <div className="notice-down-message">
                                                <span className={name.slice(name.lastIndexOf('.') + 1, name.length) + ' uploadType-img'} ></span>
                                                <p title={name.length > 60 ? name: ''}>{name.length > 60 ? name.slice(0, 58) + '..' : name}  <span>{(size / 1024 / 1024) >= 1 ?
                                                    '[' + (size / 1024 / 1024).toFixed(1) + 'MB]' : '[' + (size / 1024).toFixed(1) + 'KB]'}</span></p>
                                                {/* <a  download={detail.AttachmentName} onClick={()=>{this.downFile(detail.AttachmentUrl) }}>下载</a> */}
                                                <b className='down-file' href={url.indexOf('.mp4') === -1 && url.indexOf('.mp4') === -1 ? url : url + '?filename=' +
                                                    name.slice(0, -4)} download={name} onClick={() => { this.downFile(item) }}>下载</b>        
                                            </div>
                                        )
                                    })
                                }
                                
                            </div> : ''}
                        </div>

                    </div> : ""
                }
                
                <BtnAlert 
                visible={alertInfo.visible} 
                title={alertInfo.title} 
                data={alertInfo.data}
                smallTitle={alertInfo.smallTitle}
                onOk={alertInfo.onOk}
                onCancel={alertInfo.onCancel} />
            </div>
        )
    }
}

export default NoticeDetail;